package com.lyf.service.admin.impl;

import com.github.pagehelper.Page;
import com.lyf.constant.MessageConstant;
import com.lyf.constant.StatusConstant;
import com.lyf.context.BaseContext;
import com.lyf.dto.CategoryDTO;
import com.lyf.dto.CategoryPageQueryDTO;
import com.lyf.exception.DeletionNotAllowedException;
import com.lyf.mapper.admin.CategoryMapper;
import com.lyf.mapper.admin.DishMapper;
import com.lyf.mapper.admin.SetmealMapper;
import com.lyf.pojo.Category;
import com.lyf.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service("adminCategoryServiceImpl")
public class CategoryServiceImpl implements CategoryService {

    @Resource
    CategoryMapper categoryMapper;
    @Resource
    DishMapper dishMapper;
    @Resource
    SetmealMapper setmealMapper;

    @Override
    public void save(CategoryDTO categoryDTO) {
        Category category = new Category();
        //属性拷贝
        BeanUtils.copyProperties(categoryDTO, category);

        //分类状态默认为禁用状态0
        category.setStatus(StatusConstant.DISABLE);

        // 通过AOP 自动填充功能，填充创建时间、更新时间、创建人、更新人
        categoryMapper.insert(category);
    }

    @Override
    public void deleteById(Long id) {
        //查询当前分类是否关联了菜品，如果关联了就抛出业务异常
        Integer count = dishMapper.countByCategoryId(id);
        if(count > 0){
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        //查询当前分类是否关联了套餐，如果关联了就抛出业务异常
        count = setmealMapper.countByCategoryId(id);
        if(count > 0){
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        //删除分类数据
        categoryMapper.deleteById(id);
    }
    @Override
    public void update(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);

        // 通过AOP 自动填充功能，更新时间、更新人
        categoryMapper.update(category);
    }
    @Override
    public void startOrStop(Integer status, Long id) {
        Category category = Category.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        categoryMapper.update(category);
    }
    @Override
    public List<Category> list(Integer type) {
        return categoryMapper.list(type);
    }

    @Override
    public Page<Category> pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        return categoryMapper.pageQuery(categoryPageQueryDTO.getName(), categoryPageQueryDTO.getType());
    }


}
